package com.itedge.solutionmanager.service.domain.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itedge.infrastructure.service.domain.ISearchableEntityService;
import com.itedge.infrastructure.service.domain.impl.AbstractJpaEntityService;
import com.itedge.solutionmanager.domain.impl.Employee;

@Service
public class EmployeeService extends AbstractJpaEntityService<Employee> 
	implements ISearchableEntityService<Employee> {

	@PersistenceContext
    transient EntityManager entityManager;

	@Override
	protected EntityManager getEntityManager() {
		return this.entityManager;
	}

	@Override
	protected Class<Employee> getClassReference() {
		return Employee.class;
	}
	
	@Override
	@Transactional
    public Employee merge(Employee emp) {
		Employee merged = null;
       /* Update version property, in case employee was changed in meantime. */		
		synchronized(this) {
			Employee attached = this.entityManager.find(Employee.class, emp.getId());
			emp.setVersion(attached.getVersion());
			merged = this.entityManager.merge(emp);
		}
		this.entityManager.flush();
        return merged;
    }
	
	//TODO: rewrite to use CriteriaQuery
	@Override
	public List<Employee> findEntitiesByCriteria(Employee searchEmployee, Integer maxResults) {	
		TypedQuery<Employee> query = 
			this.entityManager.createQuery("select o from Employee o where upper(o.username) like upper(:searchName)",
					Employee.class).setParameter("searchName", '%'+searchEmployee.getUsername()+'%');
		if (maxResults != null) {
			query.setMaxResults(maxResults);
		}
		return query.getResultList();
	}

}